package com.hq.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hq.zb.dto.RoleDto;
import com.hq.zb.dto.UserDto;
import com.hq.zb.exception.BizException;
import com.hq.zb.exception.BizExceptionEnum;
import com.hq.zb.mapper.RoleMapper;
import com.hq.zb.mapper.RoleUserMapper;
import com.hq.zb.mapper.UserMapper;
import com.hq.zb.model.*;
import com.hq.zb.service.IRoleUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关系表 服务实现类
 * </p>
 *
 * @author huanghanrui
 * @since 2022-03-07
 */
@Service
@Transactional(rollbackFor= Exception.class)
public class RoleUserServiceImpl extends ServiceImpl<RoleUserMapper, RoleUser> implements IRoleUserService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Override
    public List<RoleUser> qyeryByRoleUser(RoleUser roleUser) {
        return roleUserMapper.qyeryByRoleUser(roleUser);
    }

    @Override
    public void assignUser(RoleUser roleUser) {
        if (roleUser.getUserId() != null && roleUser.getRoleId() != null) {
            //查询角色编号是否存在
            Role role = roleMapper.selectById(roleUser.getRoleId());
            if (role != null) {
                //查询用户信息
                User user = userMapper.selectById(roleUser.getUserId());
                if (user != null) {
                    String roleDept = role.getDeptCode();
                    String userDept = user.getDeptCode();
                    if(StringUtils.isNotBlank(roleDept)) {
                        //判断角色跟用户的部门匹配不匹配
                        if (!checkRole(userDept,roleDept)) {
                            //角色部门和用户部门不一致
                            throw new BizException(BizExceptionEnum.INVALID_ARGUMENT, "角色部门和用户部门不一致.");
                        }
                    }
                    roleUserMapper.insert(roleUser);
                } else {
                    //用户系统中不存在
                    throw new BizException(BizExceptionEnum.DATA_NOT_EXIST, "用户名系统中不存在.");
                }
            } else {
                //角色编号系统中不存在
                throw new BizException(BizExceptionEnum.DATA_NOT_EXIST, "角色编码系统中不存在.");
            }
        } else {
            //用户编码和角色编码不允许为空
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "用户编码和角色编码不允许为空.");
        }
    }

    @Override
    public void noAssignUser(RoleUser roleUser) {
        //先根据用户名和角色编码查询
        List<RoleUser> roleUsers = roleUserMapper.qyeryByRoleUser(roleUser);
        if (roleUsers != null && !roleUsers.isEmpty()) {
            roleUserMapper.deleteById(roleUsers.get(0));
        }
    }

    @Override
    public List<String> queryRoleName(Integer userId) {
        return roleUserMapper.queryRoleName(userId);
    }

    @Override
    public void assignRoleUser(RoleDto roleDto) {
        if (roleDto.getRoleId() == null) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "角色ID必填.");
        }
        List<UserDto> noAssignUsers = roleDto.getNoAssignUser();
        if (CollectionUtil.isNotEmpty(noAssignUsers)) {
            for (UserDto userDto : noAssignUsers) {
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("user_id", userDto.getUserId());
                deleteMap.put("role_id", roleDto.getRoleId());
                roleUserMapper.deleteByMap(deleteMap);
            }
        }

        List<UserDto> assignUsers = roleDto.getAssignUser();
        if (CollectionUtil.isNotEmpty(assignUsers)) {
            for (UserDto userDto : assignUsers) {
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("user_id", userDto.getUserId());
                deleteMap.put("role_id", roleDto.getRoleId());
                roleUserMapper.deleteByMap(deleteMap);
                RoleUser roleUser = new RoleUser();
                roleUser.setRoleId(roleDto.getRoleId());
                roleUser.setUserId(userDto.getUserId());
                roleUserMapper.insert(roleUser);
            }
        }
    }

    /**
     * 验证角色部门是否在用户部门下
     * @param userDept
     * @param roleDept
     * @return
     */
    private boolean checkRole(String userDept, String roleDept) {
        if (StringUtils.isNotEmpty(userDept) && StringUtils.isNotEmpty(roleDept) && userDept.indexOf(roleDept) < 0) {
            return false;
        }
        return true;
    }
}
